package com.liuhouse.controller;

import com.liuhouse.enums.AppHttpCodeEnum;
import com.liuhouse.exception.SystemException;
import com.liuhouse.pojo.Role;
import com.liuhouse.pojo.User;
import com.liuhouse.service.IRoleService;
import com.liuhouse.service.IUserService;
import com.liuhouse.utils.ResponseResult;
import com.liuhouse.utils.SecurityUtils;
import com.liuhouse.vo.UserInfoAndRoleIdsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private IUserService userService;


    //查询用户列表
    @GetMapping("/list")
    public ResponseResult list(User user , Integer pageNum , Integer pageSize){
        ResponseResult result = userService.selectUserPage(user, pageNum, pageSize);
        return result;
    }


    //添加用户
    @PostMapping
    public ResponseResult add(@RequestBody User user){
        //进行参数验证
        //用户姓名不能为空
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        //如果姓名不唯一
        if(!userService.checkUserNameUnique(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //检查电话是否唯一
        if(!userService.checkPhoneUnique(user)){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

        //检查邮箱是否是唯一的
        if(!userService.checkEmailUnique(user)){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //都验证通过之后进行用户的添加
        return userService.addUser(user);
    }



    //删除用户
    @DeleteMapping("/{userIds}")
    public ResponseResult remove(@PathVariable(name = "userIds")List<Long> userIds){
        //如果删除的用户中存在当前登录的用户   就不允许删除
        if(userIds.contains(SecurityUtils.getUserId())){
            return ResponseResult.errorResult(500 , "不能删除当前你正在使用的用户");
        }
        userService.removeByIds(userIds);
        return ResponseResult.okResult();
    }


    @Resource
    private IRoleService roleService;

    @GetMapping("/{userId}")
    //修改用户 - 根据id查询用户信息
    public ResponseResult getUserInfoAndRoleIds(@PathVariable("userId") Long userId){
        //查询用户对象
        User user = userService.getById(userId);
        //查询所有的角色
        List<Role> roles = roleService.selectRoleAll();
        //查询已经选择的角色id列表
        List<Long> roleIds = roleService.selectRoleIdByUserId(userId);
        //构建数据返回
        UserInfoAndRoleIdsVo vo = new UserInfoAndRoleIdsVo();
        vo.setUser(user);
        vo.setRoleIds(roleIds);
        vo.setRoles(roles);
        return ResponseResult.okResult(vo);
    }


    //更新用户信息
    @PutMapping
    public ResponseResult edit(@RequestBody User user){
        userService.updateUser(user);
        return ResponseResult.okResult();
    }


}
